define('ask', ['cookie', 'jquery', 'appConfig'], function(cookie, $, appConfig){
	//定义存放图片对象
	var imgFile = null;
	var askWhomId="";
	return function(id){
		askWhomId=id;
		$("#uploadImg").on("click", function() {
			var $selectFile = $($("#askModal form")[0]).find("input[type=file]");
			$selectFile.click();
		});
		$(".askTagGroup").delegate(".askTag","click", function() {
			$(this).toggleClass("selected");
		});
		//能力检测
		if (window.File && window.FileList && window.FileReader && window.Blob) {
			$("#fileInput").on("change", getFiles);
			//filesInput.addEventListener("change", getFiles, false);
			submitUploadImg = uploadImgClient;
		} else {
			console.log("您的浏览器不支持HTML5长传");
			submitUploadImg = uploadImgServer;
		}
		$("#submitBtn").on("click", function(event){
			if (cookie.getCookie('userId') == ''){
				alert('用户请先登录！');
				$('#top_bar .user').css('display', 'none');
				$('#top_bar .log_reg').css('display', 'inline');
				$('.user-info').css('display', 'none');
				return false;
			}
			$(this).text('上传中..');
			$(this).addClass('disabled');
			event.preventDefault();
			if(imgFile===null){
				//直接提问 
				var description = $("#askDescription").val();
				var tags=[];
				$(".askTag.selected").each(function(){
					tags.push($(this).text());
				});
				var userId = cookie.getCookie('userId');
				var teacherId=askWhomId;
				createProblem({
					teacherId:askWhomId,
					content:description,
					tag:JSON.stringify(tags)
				}, userId);
			}else{
				if(validate()){
					submitUploadImg();
				}
			}

		});
		//util.setCookie("userId","555dcfbdc9175351fa2f68e3");
	};

	//在提交问题前检验数据是否合法
	function validate(){
		var errMsg="";
		if($("#askDescription").val()=="")
		{
			errMsg+="问题描述不能为空 ";
		}
		// if(imgFile===null){
		// 	errMsg+="未选择图片";
		// }
		if(errMsg!=""){
			alert(errMsg);
			return false;
		}else {
			
			return true;
		}
	}
	function submitUploadImg() {
		//根据浏览器能力被代替为uploadImgClient或uploadImgServer之一
	}
	//清空用户的输入
	function emptyInput(){
		$("#askDescription").val("");
		$(".selectedFileName").text("");
		var fileInput = $("#fileInput") 
		fileInput.after(fileInput.clone().val("")); 
		fileInput.remove();
		imgFile=null;
	}

	//客户端直接上传

	function uploadImgClient() {

		var slashIndex = imgFile.type.indexOf("/");
		var suffix = imgFile.type.substring(slashIndex + 1);
		getUploadUrl(uploadImg, suffix, imgFile.type);

	}

	//定义获取图片信息的函数

	function getFiles(e) {
		// isUpload = false;
		e = e || window.event;
		//获取file input中的图片信息列表
		var files = e.target.files,
			//验证是否是图片文件的正则
			reg = /image\/.*/i;
		fileType = files[0].type,
		fileName = files[0].name; //如果选择了多张图片，只上传第一张
		console.log(files);

		if (!reg.test(fileType)) {
			alert("你选择的" + fileName + "文件不是图片");
			return;
		} else {
			imgFile = files[0];
			$(".selectedFileName").text(fileName);
		}
		//console.log(f);
		//var reader = new FileReader();
		//读取文件内容
		//reader.readAsDataURL(f);
		//console.log(imgFile);
	}
	//获取上传地址
	function getUploadUrl(callback, suffix, type) {
		console.log(suffix, type);
		$.ajax({
			url: appConfig.host + "/api/image-url",
			type: "POST",
			data: {
				suffix: suffix,
				contentType: type
			},
			success: function(d) {
				console.log(d);
				callback(d.url,type);
			}
		});
	}
	function uploadImg(url,fileType) {
		var reader=new FileReader();
		// console.log(fileType);
		// console.log(imgFile);
		reader.onload=function(e){
			console.log(imgFile.size);
			$.ajax({
				url:url,
				type:"PUT",
				processData:false,
				headers:{
					"Content-Type":imgFile.type,
				},
				contentType:imgFile.type,
				data:e.target.result,
				success:function(d){
					console.log("successfully upload image");
					//console.log(d);
					//创建问题
					var description = $("#askDescription").val();
					var tags=[];
					$(".askTag.selected").each(function(){
						tags.push($(this).text());
					});
					console.log(tags);
					// console.log(tags,url.substring(0,url.indexOf("?")));
					var userId = cookie.getCookie('userId');
					createProblem({
						teacherId:askWhomId,
						content:description,
						image:url.substring(0,url.indexOf("?")),
						tag:JSON.stringify(tags)
					}, userId);
				}
			});
		};
		reader.readAsArrayBuffer(imgFile);
	}
	//使用form提交文件到后台，后台再上传文件
	function uploadImgServer() {
		//从返回的iframe文档中获取图片url并创建新问题
		$("#hidden_frame").on("load", function() {
			var str = $(this.contentWindow.document.body).find("pre").html();
			var json = JSON.parse(str);
			var description = $("#askDescription").val();
			var userId = cookie.getCookie('userId');
			createProblem({
				teacherId:askWhomId,
				content: description,
				image: json.url
			}, userId);
		});
		var $form = $($("form")[0]);
		$form.submit();
	}
	function createProblem(option, ID) {
		var defaultOpt = {
			teacherId: "",
			content: "无内容",
			image: "",
			tag:[]
		};
		$.extend(defaultOpt, option);
		console.log(defaultOpt);
		$.ajax({
			url: appConfig.host + "/api/user/" + ID + "/problem",
			type: "post",
			data: defaultOpt,
			success: function(d) {
				console.log("create problem", d);
				alert("successfully ask question");
				emptyInput();
				window.location.reload();
			}
		});
	}

});



